import { createRouter, createWebHistory } from 'vue-router'
import Login from './views/Login.vue'
import Home from './views/Home.vue'
import AdminDashboard from './views/AdminDashboard.vue'
import DataAnalysis from './views/DataAnalysis.vue'
import SessionHistory from './views/SessionHistory.vue'

// 定义路由
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false,
      layout: 'blank'
    }
  },
  {
    path: '/',
    name: 'Home',
    component: Home,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/admin',
    name: 'AdminDashboard',
    component: AdminDashboard,
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('./views/UserManagement.vue')
      },
      {
        path: 'sessions',
        name: 'SessionManagement',
        component: () => import('./views/SessionManagement.vue')
      },
      {
        path: 'messages',
        name: 'MessageManagement',
        component: () => import('./views/MessageManagement.vue')
      },
      {
        path: 'rooms',
        name: 'RoomManagement',
        component: () => import('./views/RoomManagement.vue')
      },
      {
        path: 'analysis',
        name: 'DataAnalysis',
        component: DataAnalysis
      },
      {
        path: 'session-history',
        name: 'SessionHistory',
        component: SessionHistory
      }
    ]
  },
  // 重定向到登录页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要登录
  const requiresAuth = to.meta.requiresAuth
  const isLoggedIn = sessionStorage.getItem('isLoggedIn') === 'true'
  
  // 如果需要登录但未登录，则跳转到登录页
  if (requiresAuth && !isLoggedIn) {
    next('/login')
  } else if (!requiresAuth && isLoggedIn && to.path === '/login') {
    // 如果已登录且访问登录页，则跳转到首页
    next('/')
  } else {
    next()
  }
})

export default router